<template>
	<view class="record-container">
		<view class="" style="z-index: 1000; position: fixed; top: 0; left: 0; right: 0;">
			<view class="" v-show="targetsData.length>1"
				style="display: flex; justify-content: center; align-items: center; height: 30px; background-color: #F2F2F0;">
				<text>左右滑动切换不同指标页面</text>
			</view>
			<view class=""
				style="display: flex; justify-content: center; align-items: center; background-color: #fff; height: 35px;">
				<text
					style="margin-left: 5px; display: inline-block; display: flex; justify-content: center; align-items: center; height: 30px; width: 30px; border-radius: 50%;"
					v-for=" (item,index1) in targetsData.length" :key="index1"
					:style="index1 === index ? 'background-color: #3288DF;': 'background-color: #CCCCCC;'">
					{{index1+1}}</text>
			</view>
		</view>
		<view class="" style="background-color: #fff;" :style="{height: (targetsData.length> 1? '60px': '30px') }">

		</view>
		<swiper class="record-swiper" :current="index" :indicator-dots="false" :autoplay="false" :duration="500">
			<swiper-item v-for="(target,inx) in targetsData" :key="target.id">
				<wyb-slide-listener @slideLeft="onSlide" @slideRight="onSlide">
					<view class="first">
						<view class="title-box">
							<view class="title title-height">
								<text class="pl-12">指标名称</text>
							</view>
							<view class="content">
								<text>{{ target.name }}</text>
							</view>
						</view>
						<view class="des-box">
							<view class="des title-height">
								<text class="pl-12">指标说明</text>
							</view>
							<view class="content" style="display: flex;flex-wrap: wrap;flex-direction: row;">
								<text>{{ target.content }}</text>
								<u-link v-if="target.file_name"
									style="align-self: flex-end;justify-content: flex-end;margin-right: 5px;"
									:href="`${fileHost}${target.file_url}`" :text="target.file_name" :under-line="true"></u-link>
							</view>
						</view>
					</view>

					<view class="two">
						<view class="des title-height">
							<text>评价结果</text>
						</view>
						<uni-forms :ref="'commentForm'+inx" :modelValue="target.comment" label-position="top">
							<uni-forms-item required name="options" v-if="isNotNull(target.choiceType)" :rules="rules.options.rules">
								<uni-data-checkbox :multiple="target.choiceType === 2" v-model="target.comment.options"
									:localdata="target.options" :map="{text:'answer',value:'id'}" @change="checkBoxChange($event,inx)" />
							</uni-forms-item>
							<uni-forms-item label="数值录入" required name="input_value" v-else :rules="rules.input_value.rules">
								<view style="display: flex; align-items: center; color: red;">
									<uni-number-box v-model="target.comment.input_value" :min="0" :max="target.maxInput"
										@change="resultNumberChange($event,inx)"></uni-number-box>
									<text>最高{{ target.maxInput }}</text>
								</view>
							</uni-forms-item>
							<uni-forms-item :required="requiredLight" label="工作亮点" name="light" :rules="rules.light.rules"
								v-show="show[inx].showLight">
								<uni-easyinput type="textarea" v-model="target.comment.light" placeholder="请输入工作亮点" />
							</uni-forms-item>
							<uni-forms-item :required="requiredQuestion" label="存在问题" name="content" :rules="rules.question.rules"
								v-show="show[inx].showQuestion">
								<uni-easyinput type="textarea" v-model="target.comment.content" placeholder="请输入存在问题"
									@change="questionChange($event,inx)" />
							</uni-forms-item>
							<uni-forms-item required label="工作建议" name="opinions" :rules="rules.opinions.rules"
								v-show.sync="show[inx].showOpinions">
								<uni-easyinput type="textarea" v-model="target.comment.opinions" placeholder="请输入工作建议" />
							</uni-forms-item>
						</uni-forms>
					</view>
				</wyb-slide-listener>
			</swiper-item>
		</swiper>
		<view class="media" v-if="showFile()">
			<button type="primary" class="media-btn" @click="handlerPhoto">拍照</button>
			<button class="media-btn" @click="handlerVoice">录音</button>
			<button class="media-btn" @click="handlerVideo">视频</button>
		</view>
	</view>
</template>

<script>
	import {
		deepClone,
		isNotNull,
		isNull,
		getObjType
	} from "@/utils/common.js"
	import constant from "@/utils/constant.js"

	export default {
		name: "evaluate-info",
		data() {
			return {
				fileHost: constant.fileHost,
				targetsData: [],
				index: 0,
				isNotNull,
				defaultShow: {
					showQuestion: false,
					showOpinions: false,
					showLight: true,
				},
				show: [],
				rules: {
					options: {
						rules: [{
							required: true,
							errorMessage: '请选择评价结果',
						}]
					},
					input_value: {
						rules: [{
							required: true,
							errorMessage: '请输入分数',
						}]
					},
					light: {
						rules: [{
							required: true,
							errorMessage: '请输入工作亮点',
						}]
					},
					question: {
						rules: [{
							required: true,
							errorMessage: '请输入存在问题',
						}]
					},
					opinions: {
						rules: [{
							required: true,
							errorMessage: '请输入工作建议',
						}]
					}
				},
				requiredLight: true,
				requiredOpinions: true,
				requiredQuestion: true,
			};
		},
		props: {
			targetData: {
				type: Array
			},
			commentsData: {
				type: Array
			}
		},
		created() {
			this.formatData()
		},
		computed: {
			isSchool() {
				return !this.$store.state.user.isLead;
			}

		},
		methods: {
			formatData() {
				const targets = deepClone(this.targetData)
				const comments = deepClone(this.commentsData)
				targets.forEach((target, index) => {
					const isCheckbox = target.choiceType === 2;
					const uuid = uni.$u.guid();
					if (comments.length > 0) {
						comments.forEach(comment => {
							if (target.id === comment.targetId) {
								const newComment = deepClone(comment)
								if (isCheckbox) {
									newComment.options =
										getObjType(comment.options_value) === "array" ? newComment
										.options :
										newComment.options.split(",")
								}
								newComment.uuid = comment.uuid || uuid;
								target["comment"] = newComment;
								let imgUrlData = [];
								if (comment.imgUrl) {
									imgUrlData = comment.imgUrl.split(",").map(item => {
										return {
											url: item
										}
									});
								}
								const imgAppendFiles = this.$store.state.file[
									`pic_files_${newComment.uuid}`]?.appendFiles || []
								this.$store.commit('SAVE_PIC', {
									uuid: newComment.uuid,
									files: {
										originFiles: imgUrlData,
										appendFiles: imgAppendFiles
									}
								})
								let voiceUrlData = [];
								if (comment.voiceUrl) {
									voiceUrlData = comment.voiceUrl.split(",").map(item => {
										return {
											url: item
										}
									});
								}
								const voiceAppendFiles = this.$store.state.file[
									`voice_files_${newComment.uuid}`]?.appendFiles || []
								this.$store.commit('SAVE_VOICE', {
									uuid: newComment.uuid,
									files: {
										originFiles: voiceUrlData,
										appendFiles: voiceAppendFiles
									}
								})
								let videoUrlData = [];
								if (comment.videoUrl) {
									videoUrlData = comment.videoUrl.split(",").map(item => {
										return {
											url: item
										}
									});
								}
								const videoAppendFiles = this.$store.state.file[
									`video_files_${newComment.uuid}`]?.appendFiles || []
								this.$store.commit('SAVE_VIDEO', {
									uuid: newComment.uuid,
									files: {
										originFiles: videoUrlData,
										appendFiles: videoAppendFiles
									}
								})
							}
						})

					} else {

						target["comment"] = {
							options: isCheckbox ? [] : null,
							input_value: 0,
							light: "",
							content: "",
							opinions: "",
							uuid: uuid,
							options_value: isCheckbox ? [] : null
						}
					}
					this.show.push(this.defaultShow);
				});
				this.targetsData = targets;
				targets.forEach((target, index) => {
					if (isNotNull(target.choiceType)) {
						this.show[this.index].showQuestion = target.choiceType === 2;
						this.requiredLight = false;
						this.requiredQuestion = false;
					} else {
						this.requiredLight = false;
						this.requiredQuestion = false;
						this.resultNumberChange();
					}
					this.questionChange(target.comment.content, index);
				});
				this.$forceUpdate()
			},
			onSlide: function(e) {
				let type = e.type
				const target = this.targetsData[this.index];
				switch (type) {
					case 'slideLeft':
						if (this.index < this.targetsData.length - 1) {
							this.index++;
							if (isNull(target.choiceType)) {
								this.resultNumberChange();
							} else {
								this.checkBoxChange();
							}
						}
						break
					case 'slideRight':
						if (this.index > 0) {
							this.index--;
							if (isNull(target.choiceType)) {
								this.resultNumberChange();
							} else {
								this.checkBoxChange();
							}
						}
						break
				}
			},
			handlerPhoto() {
				const comment = this.targetsData[this.index].comment;
				const uuid = comment.uuid;
				uni.$u.route('/pages/school-index/media-data/photo-data', {
					uuid,
					imageUrls: JSON.stringify(comment.imgUrl ? comment.imgUrl.split(",") : [])
				});
			},
			handlerVoice() {
				const comment = this.targetsData[this.index].comment;
				const uuid = comment.uuid;
				uni.$u.route('/pages/school-index/media-data/voice-data', {
					uuid,
					voiceUrls: JSON.stringify(comment.voiceUrl ? comment.voiceUrl.split(",") : [])
				});
			},
			handlerVideo() {
				const comment = this.targetsData[this.index].comment;
				const uuid = comment.uuid;
				uni.$u.route('/pages/school-index/media-data/video-data', {
					uuid,
					videoUrls: JSON.stringify(comment.videoUrl ? comment.videoUrl.split(",") : [])
				});
			},
			showFile() {
				return this.targetsData[this.index]?.isPositive === 1;
			},
			resultNumberChange(value, inx) {
				const index = inx || this.index
				const target = this.targetsData[index];
				const isCheckbox = target.choiceType === 2;
				if (!target?.comment) {
					target["comment"] = {
						options: isCheckbox ? [] : null,
						input_value: 0,
						light: "",
						content: "",
						opinions: "",
						uuid: uni.$u.guid(),
						options_value: isCheckbox ? [] : null
					}
				}
				if (value) {
					target.comment.input_value = value;
				}
				if (!target.comment.input_value) {
					this.show[index].showLight = true;
				}
				const thisShow = deepClone(this.show[index])
				thisShow.showQuestion = target.comment.input_value && target.comment.input_value <= Number(target
					.warningLine);
				if (!thisShow.showQuestion) {
					target.comment.content = "";
					target.comment.opinions = "";
					this.questionChange();
				}
				target.comment.isProblem = thisShow.showQuestion ? 1 : 0;
				this.show[index] = thisShow
				this.targetsData[index] = target;
				this.$forceUpdate()
			},
			questionChange(value, inx) {
				const index = inx || this.index
				const target = this.targetsData[index];
				const isCheckbox = target.choiceType === 2;
				if (!target?.comment) {
					target["comment"] = {
						options: isCheckbox ? [] : null,
						input_value: 0,
						light: "",
						content: "",
						opinions: "",
						uuid: uni.$u.guid(),
						options_value: isCheckbox ? [] : null
					}
				}
				if (value) {
					target.comment.content = value;
				}
				this.targetsData[index] = target;
				this.show[index].showOpinions = isNotNull(target.comment.content) && !this.isSchool;
				this.$forceUpdate()
			},
			checkBoxChange(value, inx) {
				const index = inx || this.index
				const target = this.targetsData[index];
				if (target.choiceType === 1) {
					const thisShow = deepClone(this.show[index])
					if (value) {
						const data = value.detail.data;
						const isCaption = data.isCaption === 1;
						thisShow.showQuestion = isCaption;
						thisShow.showOpinions = isCaption && !this.isSchool;
						thisShow.showLight = !isCaption;
						if (isCaption) {
							target.comment.light = "";
							target.comment.isProblem = 1;
						} else {
							target.comment.content = "";
							target.comment.opinions = "";
							target.comment.isProblem = 0;
						}
						target.comment.options_value = data.answer;
						this.show[index] = thisShow
					} else {
						const options = target.comment.options;
						if (options) {
							const data = target.options.filter(item => {
								return item.id === options;
							});
							const isCaption = data[0].isCaption === 1;
							thisShow.showQuestion = isCaption;
							thisShow.showOpinions = isCaption && !this.isSchool;
							thisShow.showLight = !isCaption;
							target.comment.isProblem = 1;
							target.comment.options_value = data[0].answer;
							this.show[index] = thisShow
						} else {
							thisShow.showQuestion = false;
							thisShow.showOpinions = false;
							thisShow.showLight = true;
							target.comment.isProblem = 0;
							this.show[index] = thisShow
						}
					}
					this.$forceUpdate()
				} else {
					const data = value.detail.data;
					target.comment.options_value = data.map(item => {
						return item.answer;
					});
					target.comment.isProblem = 0;
				}


			},
			toJSON() {

			},
			async validate(callback) {

				this.checkAll().then((res) => {
					const {
						valid,
						error
					} = res;
					let promise;
					if (!callback && typeof callback !== 'function' && Promise) {
						promise = new Promise((resolve, reject) => {
							callback = function({
								valid,
								formData,
								error
							}) {
								valid ? resolve(formData) : reject(error);
							};
						});
					}

					const newData = valid ? deepClone(this.targetsData) : [];
					const formData = [];
					const createTime = this.createTime || uni.$u.timeFormat(new Date(),
						'yyyy-mm-dd hh:MM:ss')
					if (valid) {
						newData.forEach(item => {
							const comment = deepClone(item.comment);
							const isNumberResult = isNull(item.choiceType);
							const saveComment = {
								id: comment.id,
								targetId: item.id,
								isProblem: comment.isProblem,
								light: comment.light,
								content: comment.content,
								opinions: comment.opinions,
								createTime: createTime,
								input_value: comment.input_value,
								options_value: getObjType(comment.options_value) === "array" ?
									comment.options_value.join(",") : comment.options_value,
								options: getObjType(comment.options) === "array" ? comment.options
									.join(",") : comment.options,
								imgUrl: comment.imgUrl,
								voiceUrl: comment.voiceUrl,
								videoUrl: comment.videoUrl,
							};
							const files = [];
							const storeageFiles = [];
							if (this.showFile()) {
								const uuid = comment.uuid;
								const emptyData = {
									originFiles: [],
									appendFiles: []
								}
								const videoData = this.$store.state.file[`video_files_${uuid}`] ||
									emptyData;
								const imgData = this.$store.state.file[`pic_files_${uuid}`] ||
									emptyData;
								const voiceData = this.$store.state.file[`voice_files_${uuid}`] ||
									emptyData;
								saveComment.videoUrl = videoData.originFiles.map(item => {
									return item.url
								}).join(",");
								videoData.appendFiles.forEach(item2 => {
									files.push({
										uri: item2.url
									})
									storeageFiles.push({
										type: 'video',
										url: item2.url
									})
								});
								saveComment.imgUrl = imgData.originFiles.map(item => {
									return item.url
								}).join(",");
								imgData.appendFiles.forEach(item2 => {
									files.push({
										uri: item2.url
									})
									storeageFiles.push({
										type: 'image',
										url: item2.url
									})
								});
								saveComment.voiceUrl = voiceData.originFiles.map(item => {
									return item.url
								}).join(",");
								voiceData.appendFiles.forEach(item2 => {
									files.push({
										uri: item2.url
									})
									storeageFiles.push({
										type: 'voice',
										url: item2.url
									})
								});
							}
							saveComment.files = files;
							item.comment.storeageFiles = storeageFiles;
							formData.push(saveComment);
						})
					}
					callback && typeof callback === 'function' && callback({
						valid,
						formData,
						originalData: newData,
						error,
					});
					if (promise && callback) {
						return promise;
					} else {
						return null;
					}
				});
			},

			async checkAll() {
				const checkData = deepClone(this.targetsData);
				let result = true;
				let error = []
				const isNotSchool = !this.isSchool
				return new Promise((resolve, reject) => {
					checkData.forEach(async (item, index) => {
						let fields = ["options"];
						if (isNotNull(item.choiceType)) {
							if (item.choiceType === 1) {
								let field = []
								if (this.show[index].showLight) {
									field = ["light"];
								} else {
									field.push("content");
									if (isNotSchool) {
										field.push("opinions");
									}
								}

								fields = [...fields, ...field];
							} else {
								if (isNotNull(item.comment.content) && isNotSchool) {
									fields.push("opinions");
								}
							}
						} else {
							if (isNotNull(item.comment.content) && isNotSchool) {
								fields.push("opinions");
							}
						}
						const $ref = this.$refs["commentForm" + index][0];
						await $ref.validateField(fields, (err, formData) => {
							if (err) {
								result = result ? false : result;
								error.push({
									formIndex: index,
									error: err
								});
							}
							if (index === checkData.length - 1) {
								resolve({
									valid: result,
									error
								});
							}
						});

					})
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	page {
		position: relative;
	}

	.record-container {
		font-size: 20px;

		.record-swiper {
			height: 120vh;
		}

		.two {
			padding: 20px 12px 10px;

			.text-area-box {
				margin: 20px 0;
			}
		}

		.title-height {
			height: 7vh;
			line-height: 7vh;
			background-color: #F2F2F0;
		}

		.content {
			display: flex;
			align-items: center;
			background-color: #fff;
			height: auto;
			padding: 12px 12px;
		}

		.pl-12 {
			padding-left: 12px;
		}


		.media {
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
			height: 8vh;
			display: flex;
		}
	}


	// /deep/ .is-disabled {
	// 	background-color: #ffffff !important;
	// 	color: #0d0d0d !important;
	// }

	// /deep/ .uni-swiper-dots {
	// 	// 指示点整个区域的位置
	// 	top: 5px;
	// }

	// /deep/ .uni-swiper-dot {
	// 	// 指示点元素默认样式
	// 	width: 9rpx !important;
	// 	height: 9rpx !important;
	// 	background: #b731c0 !important;
	// }

	// /deep/ .uni-swiper-dot-active {
	// 	// 指示点元素激活（当前选中）状态样式
	// 	width: 32rpx !important;
	// 	height: 8rpx !important;
	// 	background: #55ff00 !important;
	// 	border-radius: 4rpx;
	// }
</style>